<template>
  <div class="societies-container">
    <!-- 顶部横幅 -->
    <div class="banner">
      <div class="banner-content">
        <h1>社团联盟</h1>
        <p>发现兴趣，结识志同道合的朋友</p>
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索社团名称、分类或关键词"
            class="search-input"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button icon="Search" @click="handleSearch"></el-button>
            </template>
          </el-input>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 筛选条件 -->
      <div class="filter-section">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="8" :md="6">
            <el-select v-model="filterCategory" placeholder="选择分类" clearable @change="handleFilterChange">
              <el-option
                v-for="category in clubs_tags"
                :key="category.value"
                :label="category.label"
                :value="category.value"
              />
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="8" :md="6"> 
            <el-select v-model="filterStatus" placeholder="选择状态" clearable @change="handleFilterChange">
              <el-option
                v-for="status in member_status"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              />
            </el-select>
          </el-col>
          <el-col :xs="24" :sm="8" :md="6">
            <el-select v-model="sortBy" placeholder="排序方式" @change="handleFilterChange">
              <el-option label="最新创建" value="createdAt" />
              <el-option label="成员最多" value="memberCount" />
              <el-option label="名称排序" value="name" />
            </el-select>
          </el-col>
          
          <el-col :xs="24" :sm="24" :md="6" class="filter-actions">
            <el-button type="primary" @click="handleFilter(1)">我的收藏</el-button>
            <el-button type="primary" @click="handleFilter(2)">筛选</el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-col>
        </el-row>
      </div>
    

      

      <!-- 社团列表 -->
      <div class="clubs-section">
        <div v-if="loading" class="loading-container">
          <el-skeleton :rows="6" animated />
        </div>
        
        <template v-else>
          <div v-if="clubsList.length === 0" class="no-data">
            <el-empty description="未找到符合条件的社团" />
          </div>
          
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" v-for="club in clubsList" :key="club.clubId">
              <div class="club-card">
                <div class="club-header">
                  <div class="club-logo">
                    <img :src="getImageUrl(club.logo) || '/img/default-club-logo.png'" :alt="club.name" />
                  </div>
                  <div class="club-info">
                    <h3 class="club-name">{{ club.name }}</h3>
                    <p class="club-category">{{ club.categoryName }}</p>
                    <div class="club-stats">
                      <span class="member-count">
                        <el-icon><User /></el-icon> {{ club.memberCount }} 成员
                      </span>
                      <el-tag size="small" :type="getStatusTagType(club.userStatus)">
                        {{ getStatusLabel(club.userStatus) }}
                      </el-tag>
                    <el-icon 
                        class="favorite-icon" 
                        :class="{ 'is-favorite': club.isFavorite }" 
                        @click.stop="toggleFavorite(club)"
                      >
                        <Star v-if="!club.isFavorite" />
                        <StarFilled v-else />
                      </el-icon>

                    </div>
                  </div>
                </div>
                <div class="club-description">
                  <p>{{ truncateFilter(club.description || '暂无描述', 80) }}</p>
                </div>
                <div class="club-footer">
                  <div class="club-actions">
                    <el-button size="small" type="primary" @click.stop="viewClubDetail(club)">
                      查看详情
                    </el-button>

                  </div>

                </div>
              </div>
            </el-col>
          </el-row>
        </template>

        <!-- 分页 -->
        <div class="pagination-wrapper" v-if="clubsList.length > 0">
          <el-pagination
            background
            layout="prev, pager, next"
            :current-page="queryParams.pageNum"
            :page-size="queryParams.pageSize"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>


        <!-- 添加或修改社团对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="clubsRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="申请理由" prop="applyReason">
          <el-input v-model="form.applyReason" type="textarea" placeholder="申请理由" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 社团详情对话框 -->
    <el-dialog
      title="社团详情"
      v-model="detailDialogVisible"
      width="800px"
      :before-close="handleCloseDetail"
    >
      <div v-if="selectedClub" class="club-detail">
        <div class="detail-header">
          <div class="detail-logo">
            <img :src="getImageUrl(selectedClub.logo) || '/img/default-club-logo.png'" :alt="selectedClub.name" />
          </div>
          <div class="detail-info">
            <h2>{{ selectedClub.name }}</h2>
            <p class="detail-category">
              <el-icon><Collection /></el-icon> {{ selectedClub.categoryName}}
            </p>
            <div class="detail-stats">
              <span>
                <el-icon><User /></el-icon> {{ selectedClub.memberCount }} 成员
              </span>
              <span>
                <el-icon><Clock /></el-icon> {{ parseTime(selectedClub.createdAt) }}
              </span>
              <span>
                <el-tag :type="getStatusTagType(selectedClub.userStatus)">
                  {{ getStatusLabel(selectedClub.userStatus) }}
                </el-tag>
              </span>
            </div>
          </div>
        </div>
        
        <el-divider></el-divider>
        
        <div class="detail-content">
          <h3><el-icon><Document /></el-icon> 社团介绍</h3>
          <p>{{ selectedClub.description || '暂无描述' }}</p>
          
          <h3><el-icon><Postcard /></el-icon> 加入条件</h3>
          <p>{{ selectedClub.requirements || '无特殊要求' }}</p>
          
          <div class="detail-tags" v-if="selectedClub.tags && selectedClub.tags.length">
            <h3><el-icon><PriceTag /></el-icon> 社团标签</h3>
            <div class="tags-container">
              <el-tag v-for="tag in selectedClub.tags" :key="tag.id" type="info">
                {{ tag.tag }}
              </el-tag>
            </div>
          </div>
        </div>
        
        <div class="detail-actions">
          <el-button  type="primary"  v-if="selectedClub.userStatus==0" @click="apply(selectedClub.clubId)" size="large">
            <el-icon><Connection /></el-icon> 申请加入
          </el-button>
          <el-button  type="primary"  v-if="selectedClub.userStatus==1" @click="toUnapply(selectedClub.clubId)" size="large">
            <el-icon><Connection /></el-icon> 撤销申请
          </el-button>
          <el-button @click="handleCloseDetail" size="large">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { Star, StarFilled } from '@element-plus/icons-vue'

import { 
  listByUser, 
  getClubsByUser 
} from "@/api/system/clubs";
import { 
  delFavorites, 
  addFavorites 
} from "@/api/system/favorites";
import { 
  addMembers,unapply 
} from "@/api/system/members";

import { parseTime } from "@/utils/ruoyi";
import { 
  User, 
  Collection, 
  Clock, 
  Document, 
  Postcard, 
  PriceTag, 
  Connection 
} from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();
const { member_status ,clubs_tags} = proxy.useDict("member_status","clubs_tags");
const form = ref({});
// 搜索关键词
const searchKeyword = ref("");
// 筛选条件
const filterCategory = ref(null);
const filterStatus = ref(""); // 默认显示已通过的社团
const sortBy = ref("createdAt");
// 社团列表
const clubsList = ref([]);
// 分页参数
const queryParams = reactive({
  isFavorite: 2,
  pageNum: 1,
  pageSize: 9,
  name: null,
  categoryName: null,
  userStatus: null,
  sortBy: "createdAt"
});
const total = ref(0);
const loading = ref(true);
// 详情对话框
const detailDialogVisible = ref(false);
const open = ref(false);
const selectedClub = ref(null);
const title = ref("申请加入社团");

const rules = {
  applyReason: [{ required: true, message: "申请理由不能为空", trigger: "blur" }]
};

// 获取图片完整URL
const getImageUrl = (url) => {
  if (!url) return '';
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  return import.meta.env.VITE_APP_BASE_API + url;
};



const toggleFavorite = async (club) => {
  try {
    if(!club.isFavorite){
      //添加
      const response = await addFavorites(club);
      club.isFavorite = response.data.id;
    }else{
      //删除
      await delFavorites(club.isFavorite);
      club.isFavorite = null;
    }
  } catch (error) {
    console.error("收藏操作失败:", error);
    proxy.$modal.msgError("操作失败");
  }
}



// 获取社团列表
const getClubsByUserList = async () => {
  loading.value = true;
  try {
    const response = await listByUser(queryParams);
    clubsList.value = response.rows;
    total.value = response.total;
  } catch (error) {
    console.error("获取社团列表失败:", error);
  } finally {
    loading.value = false;
  }
};



// 搜索
const handleSearch = () => {
  queryParams.name = searchKeyword.value || null;
  queryParams.pageNum = 1;
  getClubsByUserList();
};

// 筛选
const handleFilter = (isFavorite) => {
  queryParams.categoryName = filterCategory.value || null;
  queryParams.userStatus = filterStatus.value || null;
  queryParams.sortBy = sortBy.value;
  if(isFavorite === 1){
    queryParams.isFavorite = isFavorite;
  }else{
    queryParams.isFavorite = 2;
  }
  queryParams.pageNum = 1;
  getClubsByUserList();
};

// 处理筛选条件变化
const handleFilterChange = () => {
  handleFilter(2);
};

// 重置筛选
const resetFilter = () => {
  searchKeyword.value = "";
  filterCategory.value = null;
  filterStatus.value = "";
  sortBy.value = "createdAt";
  queryParams.name = null;
  queryParams.categoryName = null;
  queryParams.userStatus = null;
  queryParams.sortBy = "createdAt";
  queryParams.isFavorite = 2;
  queryParams.pageNum = 1;
  getClubsByUserList();
};

// 分页
const handleCurrentChange = (page) => {
  queryParams.pageNum = page;
  getClubsByUserList();
};



// 获取状态标签
const getStatusLabel = (status) => {
  const statusObj = member_status.value.find(item => item.value === status.toString());
  return statusObj ? statusObj.label : '未申请';
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  const types = {
    '1': 'warning',   // 待审核
    '2': 'success',   // 已通过
    '3': 'danger',    // 已拒绝
  };
  return types[status] || 'info';
};

// 查看社团详情
const viewClubDetail = async (club) => {
  try {
    const response = await getClubsByUser(club.clubId);
    selectedClub.value = response.data;
    detailDialogVisible.value = true;
  } catch (error) {
    console.error("获取社团详情失败:", error);
    proxy.$modal.msgError("获取社团详情失败");
  }
};

// 关闭详情对话框
const handleCloseDetail = () => {
  detailDialogVisible.value = false;
  selectedClub.value = null;
};



const apply = (clubId) => {
  detailDialogVisible.value = false;
  open.value = true;
  form.value = {
    clubId: clubId,
    applyReason: ''
  };
};
const toUnapply = (clubId) => {
 unapply(clubId).then(response => {
          proxy.$modal.msgSuccess("撤销成功");
          open.value = false;
          getClubsByUserList();
        });
  
};

const submitForm = async() => {
  proxy.$refs["clubsRef"].validate(valid => {
    if (valid) {
      addMembers(form.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getClubsByUserList();
      });
    }
  });
};

const cancel = () => {
  open.value = false;
  form.value = {};
  proxy.resetForm("clubsRef");
};

// 自定义过滤器 - 截断文本
const truncateFilter = (value, length) => {
  if (!value) return '';
  if (value.length <= length) return value;
  return value.substring(0, length) + '...';
};

onMounted(() => {
  getClubsByUserList();
});
</script>

<style scoped lang="scss">
.societies-container {
  min-height: 100vh;
  background-color: #f8f9fa;
  font-family: 'Helvetica Neue', Arial, sans-serif;
}

.banner {
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  color: white;
  padding: 80px 0 60px;
  text-align: center;
  position: relative;
  overflow: hidden;
  
  &::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="none"><polygon points="0,100 100,0 100,100" fill="rgba(255,255,255,0.05)"/></svg>');
    background-size: cover;
  }
}

.banner-content {
  position: relative;
  z-index: 1;
  max-width: 800px;
  margin: 0 auto;
  padding: 0 20px;
  
  h1 {
    font-size: 3.5rem;
    margin-bottom: 15px;
    font-weight: 700;
    text-shadow: 0 2px 4px rgba(0,0,0,0.2);
    letter-spacing: -0.5px;
  }
  
  p {
    font-size: 1.4rem;
    margin-bottom: 40px;
    opacity: 0.9;
    font-weight: 300;
  }
}

.search-box {
  max-width: 600px;
  margin: 0 auto;
  
  .search-input {
    border-radius: 30px;
    overflow: hidden;
    box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    
    :deep(.el-input__inner) {
      height: 48px;
      padding: 0 20px;
      border-radius: 30px 0 0 30px;
      border: none;
      font-size: 16px;
    }
    
    :deep(.el-input-group__append) {
      background: #4e54c8;
      border: none;
      border-radius: 0 30px 30px 0;
      padding: 0 25px;
      
      .el-button {
        color: white;
        font-size: 18px;
      }
    }
  }
}

.main-content {
  max-width: 1200px;
  margin: -40px auto 40px;
  padding: 0 20px;
  position: relative;
  z-index: 2;
}

.filter-section {
  background: white;
  padding: 20px;
  border-radius: 12px;
  margin-bottom: 30px;
  box-shadow: 0 6px 16px rgba(0,0,0,0.08);
  
  .el-row {
    margin-bottom: -10px;
  }
  
  .el-col {
    margin-bottom: 10px;
  }
  
  .el-select {
    width: 100%;
  }
  
  .filter-actions {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}

.clubs-section {
  margin-bottom: 40px;
}

.club-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
  transition: all 0.3s ease;
  cursor: pointer;
  height: 100%;
  display: flex;
  flex-direction: column;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 24px rgba(0,0,0,0.12);
  }
}

.club-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.club-logo {
  width: 70px;
  height: 70px;
  border-radius: 12px;
  overflow: hidden;
  margin-right: 15px;
  flex-shrink: 0;
  background: #f0f2f5;
  display: flex;
  align-items: center;
  justify-content: center;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.club-info {
  flex: 1;
  min-width: 0;
}

.club-name {
  margin: 0 0 5px 0;
  font-size: 1.25rem;
  font-weight: 600;
  color: #1a1a1a;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.club-category {
  margin: 0 0 8px 0;
  color: #6c757d;
  font-size: 0.9rem;
}

.club-stats {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
  
  .member-count {
    color: #6c757d;
    font-size: 0.9rem;
    display: flex;
    align-items: center;
    
    .el-icon {
      margin-right: 4px;
      font-size: 0.9rem;
    }
  }
}

.club-description {
  margin-bottom: 15px;
  flex: 1;
  
  p {
    margin: 0;
    color: #495057;
    line-height: 1.6;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
    font-size: 0.95rem;
  }
}

.club-footer {
  display: flex;
  justify-content: flex-end;
}

.pagination-wrapper {
  text-align: center;
  margin-top: 40px;
}

.loading-container {
  padding: 30px 0;
}

.no-data {
  padding: 60px 0;
  text-align: center;
}

/* 详情对话框样式 */
.club-detail {
  padding: 10px 0;
}

.detail-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.favorite-icon {
  cursor: pointer;
  font-size: 1.2rem;
  color: #ccc;
  transition: all 0.3s ease;
  
  &:hover {
    color: #ffc107;
    transform: scale(1.1);
  }
  
  &.is-favorite {
    color: #ffc107;
  }
}

.detail-logo {
  width: 100px;
  height: 100px;
  border-radius: 12px;
  overflow: hidden;
  margin-right: 25px;
  flex-shrink: 0;
  background: #f0f2f5;
  
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.detail-info {
  flex: 1;
  
  h2 {
    margin: 0 0 8px 0;
    color: #1a1a1a;
    font-size: 1.8rem;
  }
  
  .detail-category {
    margin: 0 0 12px 0;
    color: #6c757d;
    font-size: 1.1rem;
    display: flex;
    align-items: center;
    
    .el-icon {
      margin-right: 8px;
      font-size: 1.2rem;
    }
  }
}

.detail-stats {
  display: flex;
  gap: 20px;
  color: #6c757d;
  font-size: 0.95rem;
  flex-wrap: wrap;
  
  span {
    display: flex;
    align-items: center;
    
    .el-icon {
      margin-right: 6px;
      font-size: 1rem;
    }
  }
}

.detail-content {
  h3 {
    margin: 25px 0 15px 0;
    color: #1a1a1a;
    font-size: 1.3rem;
    display: flex;
    align-items: center;
    
    .el-icon {
      margin-right: 10px;
      font-size: 1.2rem;
      color: #4e54c8;
    }
  }
  
  p {
    margin: 0 0 20px 0;
    line-height: 1.7;
    color: #495057;
    font-size: 1rem;
  }
}

.detail-tags {
  .tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-top: 10px;
    
    .el-tag {
      font-size: 0.95rem;
      padding: 8px 14px;
    }
  }
}

.detail-actions {
  text-align: center;
  margin-top: 40px;
  padding-top: 20px;
  border-top: 1px solid transparent;
  
  .el-button {
    min-width: 180px;
    margin: 0 10px;
  }
}

/* 响应式设计 */
@media (max-width: 992px) {
  .banner {
    padding: 60px 0 40px;
  }
  
  .banner-content h1 {
    font-size: 2.8rem;
  }
  
  .banner-content p {
    font-size: 1.2rem;
  }
}

@media (max-width: 768px) {
  .banner-content h1 {
    font-size: 2.3rem;
  }
  
  .banner-content p {
    font-size: 1.1rem;
  }
  
  .detail-header {
    flex-direction: column;
    text-align: center;
  }
  
  .detail-logo {
    margin-right: 0;
    margin-bottom: 20px;
  }
  
  .detail-stats {
    justify-content: center;
  }
  
  .filter-actions {
    justify-content: center;
  }
}

@media (max-width: 576px) {
  .banner {
    padding: 50px 0 30px;
  }
  
  .banner-content h1 {
    font-size: 2rem;
  }
  
  .club-card {
    padding: 15px;
  }
  
  .club-logo {
    width: 60px;
    height: 60px;
  }
  
  .detail-actions {
    .el-button {
      min-width: 140px;
      margin-bottom: 10px;
    }
  }
}
</style>